package edu.sdwu.liqing.qasystem.controller;


import edu.sdwu.liqing.qasystem.annotation.HasRole;
import edu.sdwu.liqing.qasystem.annotation.Login;

import edu.sdwu.liqing.qasystem.entity.QaUser;
import edu.sdwu.liqing.qasystem.model.Response;
import edu.sdwu.liqing.qasystem.service.IQaUserService;
import edu.sdwu.liqing.qasystem.util.JWTUtil;
import edu.sdwu.liqing.qasystem.util.RequestUtil;
import edu.sdwu.liqing.qasystem.util.TokenStoreUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * <p>
 * 用户表  前端控制器
 * </p>
 *
 * @author liqing@sdwu.edu
 * @since 2020-03-22
 */
@RestController
@RequestMapping("api/user")
public class QaUserController {

    @Autowired
    IQaUserService userService;

    @Autowired
    RequestUtil requestUtil;

    @PostMapping("login")
    public Response<String> login(String username, String password) {
        if (userService.login(username, password)) {
            //如果登录成功
            //签发token
            String token = JWTUtil.createToken(null, username);
            return Response.create(200, "登陆成功", token);
        }
        return Response.error(null);
    }

    //做一个测试登录的接口
    @Login
    @GetMapping
    public Response<QaUser> currentUser() {
        return Response.ok(requestUtil.getCurrentUser());
    }

    @Login
    @PostMapping("logout")
    public Response<String> logout() {
        TokenStoreUtil.remove(requestUtil.getToken());
        return Response.ok("成功登出");
    }

    @HasRole({"ADMIN"})
    @PostMapping
    public Response<QaUser> save(@RequestBody QaUser user) {
        if (userService.save(user)) {
            return Response.ok(user);
        }
        return Response.error("新建用户失败，系统有相同账户");
    }



}

